//
//  UIPickerController.m
//  cutter
//
//  Created by mac on 15/12/15.
//  Copyright © 2015年 e360. All rights reserved.
//
#import "AssetsPicker.h"
#import <MobileCoreServices/MobileCoreServices.h>

//
@interface PHPhotoAsset : NSObject
+(NSArray*)fetchGroup;
+(NSArray*)fetchCollection:(PHAssetCollection *)collection;
+(UIImage*)fetchAsset:(PHAsset *)asset size:(CGSize)size;
@end
@implementation PHPhotoAsset
+(NSArray*)fetchGroup{
    NSMutableArray *groups = [NSMutableArray array];
    PHFetchResult *album = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    [album enumerateObjectsUsingBlock:^(PHCollection *obj, NSUInteger idx, BOOL *stop) {
        if ([obj isMemberOfClass:[PHAssetCollection class]]) {
            PHAssetCollection *collection = (PHAssetCollection*) obj;
            [groups addObject:collection];
        }
    }];
    return groups;
}
+(NSArray*)fetchCollection:(PHAssetCollection *)collection{
    if (collection) {
        NSMutableArray *results = [NSMutableArray array];
        PHFetchResult *assets = [PHAsset fetchAssetsInAssetCollection:collection options:nil];
        for (PHAsset *asset in assets) {
            [results addObject:asset];
        }
        return results;
    }
    return nil;
}
+(UIImage*)fetchAsset:(PHAsset *)asset size:(CGSize)size{
    if (asset) {
        PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
        [options setSynchronous:YES];
        //
        if (CGSizeEqualToSize(size, CGSizeZero)) {
            size.width = asset.pixelWidth;
            size.height = asset.pixelHeight;
        }
        //
        NSMutableArray *results = [NSMutableArray array];
        [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage *result, NSDictionary *info) {
            [results addObject:result];
        }];
        return [results firstObject];
    }
    return nil;
}
@end
//相册
@interface AssetsPickerPhotosGroupsCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@property (weak, nonatomic) IBOutlet UILabel *nameView;
@end
@implementation AssetsPickerPhotosGroupsCell
@end
@implementation AssetsPickerPhotosGroups
-(void)viewDidLoad{
    [super viewDidLoad];
    [self setGroups:[PHPhotoAsset fetchGroup]];
}
//
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.groups count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    AssetsPickerPhotosGroupsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier"];
    PHAssetCollection *group = [self.groups objectAtIndex:indexPath.row];
    NSArray *allAsset = [PHPhotoAsset fetchCollection:group];
    PHAsset *asset = [allAsset firstObject];
    if (asset) {
        UIImage *image = [PHPhotoAsset fetchAsset:asset size:CGSizeMake(100, 100)];
        if (image) {
            [cell.iconView setImage:image];
        }
    }
    [cell.nameView setText:[NSString stringWithFormat:@"%@\n%ld",group.localizedTitle, (long)[allAsset count]]];
    return cell;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(nullable id)sender{
    if ([segue.destinationViewController isKindOfClass:AssetsPickerPhotos.class]) {
        NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
        AssetsPickerPhotos *destination = segue.destinationViewController;
        [destination setGroup:[self.groups objectAtIndex:indexPath.row]];
        [destination setOnSelected:self.onSelected];
    }
}
-(IBAction)closeTouch:(id)sender {
    if (self.onSelected) {
        self.onSelected(self, nil);
    }
}
@end

@implementation AssetsPickerPhotos
-(void)viewDidLoad{
    [super viewDidLoad];
    //
    [self setColumn:4];
    [self setTitle:[self.group localizedTitle]];
    [self setAssets:[PHPhotoAsset fetchCollection:self.group]];
}
- (IBAction)backTouch:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([segue.destinationViewController isKindOfClass:AssetsPickerSetName.class]) {
        NSIndexPath *indexPath = [self.collectionView indexPathForCell:sender];
        PHAsset *asset = [self.assets objectAtIndex:indexPath.row];
        UIImage *image = [PHPhotoAsset fetchAsset:asset size:CGSizeMake(600, 600)];
        //
        AssetsPickerSetName *fileName = segue.destinationViewController;
        [fileName setOnSelected:self.onSelected];
        [fileName setImage:image];
    }
}
//
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [self.assets count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    PHAsset *asset = [self.assets objectAtIndex:indexPath.row];
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
    //
    UIImageView *imageView = [cell.contentView.subviews firstObject];
    if (imageView == nil) {
        imageView = [[UIImageView alloc] initWithFrame:cell.bounds];
        [imageView setAutoresizingMask:UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight];
        [imageView setContentMode:UIViewContentModeScaleAspectFill];
        [cell.contentView addSubview:imageView];
        [imageView.layer setMasksToBounds:YES];
    }
    UIImage *image = [PHPhotoAsset fetchAsset:asset size:CGSizeMake(100, 100)];
    [imageView setImage:image];
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger temp = self.column - 1;
    NSInteger size = (collectionView.bounds.size.width - temp) / self.column;
    if (indexPath.item % self.column == temp) {
        size = collectionView.bounds.size.width - temp - size * temp;
    }
    return CGSizeMake(size, size);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsZero;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 1;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 1;
}
@end


//分组
@implementation AssetsPickerGroups
- (IBAction)closeTouch:(id)sender {
    if (self.onSelected) {
        self.onSelected(self, nil);
    }
}
- (IBAction)makeTouch:(id)sender {
    NSMutableDictionary *data = [NSMutableDictionary dictionary];
    [data setValue:self.nameView.text forKey:@"dirname"];
    [data setValue:@"0" forKey:@"parentid"];
    if (self.onSelected) {
        self.onSelected(self, data);
    }
}
@end

//相机
@implementation AssetsPickerCamera
-(void)viewDidLoad{
    [super viewDidLoad];
    //
    [self setVideoQuality:UIImagePickerControllerQualityTypeHigh];
    [self setSourceType:UIImagePickerControllerSourceTypeCamera];
    [self setDelegate:self];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString*)kUTTypeImage]) {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        if(image.imageOrientation != UIImageOrientationUp){
            UIGraphicsBeginImageContext(image.size);
            [image drawInRect:(CGRect){.origin=CGPointZero,.size=image.size}];
            image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
        }
        [self setImage:image];
        [self performSegueWithIdentifier:@"setImageName" sender:nil];
    }
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([segue.destinationViewController isKindOfClass:UINavigationController.class]) {
        UINavigationController *ctrl = segue.destinationViewController;
        if ([[ctrl.viewControllers firstObject] isKindOfClass:AssetsPickerSetName.class]) {
            AssetsPickerSetName *imageName = [ctrl.viewControllers firstObject];
            [imageName setOnSelected:self.onSelected];
            [imageName setImage:self.image];
        }
    }
}
@end

//图片名
@implementation AssetsPickerSetName
- (IBAction)closeTouch:(id)sender {
    if (self.onSelected) {
        self.onSelected(self, nil);
    }
}
- (IBAction)makeTouch:(id)sender {
    NSMutableDictionary *data = [NSMutableDictionary dictionary];
    [data setValue:[self.directory objectForKey:@"dirname"] forKey:@"dirname"];
    [data setValue:[self.directory objectForKey:@"id"] forKey:@"parentid"];
    if (self.image) {
        NSMutableDictionary *file = [NSMutableDictionary dictionary];
        [file setValue:self.nameView.text forKey:@"name"];
        [file setValue:self.image forKey:@"image"];
        [data setValue:file forKey:@"file"];
    }
    if (self.onSelected) {
        self.onSelected(self, data);
    }
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([segue.destinationViewController isKindOfClass:AssetsPickerSetGroup.class]) {
        __weak AssetsPickerSetName *this = self;
        AssetsPickerSetGroup *imageGroup = segue.destinationViewController;
        [imageGroup setOnSelected:^(id target, id result){
            if (result) {
                id temp = [result objectForKey:@"dirname"];
                [this.groupView setText:temp];
                [this setDirectory:result];
            }
            [this.navigationController popViewControllerAnimated:YES];
        }];
    }
}
@end


//图片分组
@interface AssetsPickerSetGroupInput : UITableViewCell
@property(nonatomic, weak) IBOutlet UITextField *nameView;
@end
@implementation AssetsPickerSetGroupInput
@end
@interface AssetsPickerSetGroupCell : UITableViewCell
@property(nonatomic, weak) IBOutlet UILabel *nameView;
@end
@implementation AssetsPickerSetGroupCell
@end
@implementation AssetsPickerSetGroup
-(void)viewDidLoad{
    [super viewDidLoad];
    [self setData:[AppData userMatchAssetDirectory:nil]];
}
-(IBAction)backTouch:(id)sender {
    if (self.onSelected) {
        self.onSelected(self, nil);
    }
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (self.onSelected && [textField.text length] > 0) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setValue:textField.text forKey:@"dirname"];
        if (self.onSelected) {
            self.onSelected(self, dic);
        }
    }
    return YES;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return nil;
    }
    return @"已有分组";
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }
    return [self.data count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        AssetsPickerSetGroupInput *cell = [tableView dequeueReusableCellWithIdentifier:@"inputIdentifier"];
        [cell.nameView setDelegate:self];
        [self setNameView:cell.nameView];
        return cell;
    }
    //
    id item = [self.data objectAtIndex:indexPath.row];
    AssetsPickerSetGroupCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier"];
    [cell.nameView setText:[item objectForKey:@"dirname"]];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        if (self.onSelected) {
            self.onSelected(self, [self.data objectAtIndex:indexPath.row]);
        }
    }
}
@end

//
@implementation AssetsPicker
- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(nullable id)sender{
    if ([identifier isEqualToString:@"AssetsCamera"]) {
        return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
    }
    return YES;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    id destination = segue.destinationViewController;
    if ([destination respondsToSelector:@selector(setOnSelected:)]) {
        [destination setOnSelected:self.onSelected];
        return;
    }
    //
    if ([destination isKindOfClass:UINavigationController.class]) {
        UINavigationController *navigation = destination;
        destination = [[navigation viewControllers] firstObject];
    }
    if ([destination respondsToSelector:@selector(setOnSelected:)]) {
        [destination setOnSelected:self.onSelected];
    }
}
@end